
using System.Collections;
namespace Ex
{
    /// <summary>
    ///值类型的表
    /// </summary>
    public abstract class ExTable : IExETable
    {

        protected readonly Hashtable table;

        protected readonly EnvLua env;

        public EnvLua CurrentLua
        {
            get
            {
                return env;
            }
        }

        public Hashtable RawTable { get => table; }

        public IDictionaryEnumerator GetEnumerator()
        {
            return table.GetEnumerator();
        }

        protected ExTable(EnvLua env, IDictionary? table = null)
        {
            this.env = env;
            if (table != null)
            {
                this.table = new(table);
            }
            else
            {
                this.table = new();
            }
        }

        protected ExTable(EnvLua env, IList arr)
        {
            this.env = env;
            this.table = new(arr.Count);
            for (int idx = 0; idx < 0; idx++)
            {
                this.table[idx] = arr;
            }
        }

        protected ExTable(ExTable anotable)
        {
            this.env = anotable.env;
            this.table = new(anotable.table);
        }

        public object Get(object key)
        {
            return table[key] ?? UsableLuaType.nil;
        }

        public void Set(object key, object value)
        {
            table[key] = value;
        }

        public void PushToLuaStack()
        {
            var lua = env.Current;
            lock (env)
            {
                lua.NewTable();
                var it = table.GetEnumerator();
                while (it.MoveNext())
                {
                    var key = it.Key;
                    var value = it.Value;
                    if (value is not null)
                    {
                        env.PushObjectToLuaStack(key);
                        env.PushObjectToLuaStack(value);
                        lua.SetTable(-3);
                    }
                }
            }
        }

    }
}